package com.dream.system.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder.In;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.jni.FileInfo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dream.common.BuildEntityClass;
import com.dream.common.ClassUtil;
import com.dream.common.DateTools;
import com.dream.common.FileUpload;
import com.dream.common.FreemakerUtil;
import com.dream.common.SuperController;
import com.dream.model.Param;
import com.dream.model.Table_Info;
import com.dream.system.service.DynamicFormService;
import com.hxtt.sql.dy;

@RequestMapping("/dynamicForm/dynamicFormAction.do")
@SuppressWarnings("all")
@Controller
public class DynamicFormAction extends SuperController{


	private  String basePackage = "com.dream.model";
	
	@Autowired
	private DynamicFormService dynamicFormServiceImpl;
	
	@RequestMapping(params = "method=login")
	public String login(){
		return "main";
	}
	@RequestMapping(params = "method=loadMenuJsonData")
	@ResponseBody
	public void loadMenuJsonData(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String jsonpath = request.getServletContext().getRealPath("config")+File.separator+"menu.json";
		FileInputStream fileIn = new FileInputStream(new File(jsonpath));
		byte[] b = new byte[fileIn.available()];
		fileIn.read(b);
		fileIn.close();
	
		JSONArray json = JSONArray.fromObject(new String(b,"utf-8"));
		
		outData(response, json);
	
	}
	@RequestMapping(params = "method=createTable")
	@ResponseBody
	public void createTable(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject resultJson = new JSONObject();
		try{
			String jsonStr = request.getParameter("formData");
			String table_en_name = request.getParameter("table_en_name");
			String table_cn_name = request.getParameter("table_cn_name");
			Map<String, Object> map = new HashMap<String, Object>();
			List<Param> list = new ArrayList<Param>();
			StringBuffer sql = new StringBuffer();
			String path = request.getSession().getServletContext().getRealPath("../");
			System.out.println(path);
			
			sql.append("create table ");
			sql.append(table_en_name);
			sql.append("(table_id varchar(255) primary key not null,");
			sql.append("createTime varchar(255) ,");
			sql.append("showTime varchar(255) ,");
			
			map.put("tableName", FreemakerUtil.lowStr(table_en_name));
			map.put("className", FreemakerUtil.capStrFirst(table_en_name));
			map.put("packPath", basePackage);
			
			JSONArray ja = JSONArray.fromObject(jsonStr);
			
			for(int i = 0;i < ja.size();i++){
				JSONObject json = ja.getJSONObject(i);
				Param p = new Param();
				p.setClassName(FreemakerUtil.lowStrFirst(json.getString("column")));
				p.setClassType("String");
				sql.append(FreemakerUtil.lowStrFirst(json.getString("column"))+" varchar(255),");
				list.add(p);
			}
			
			map.put("paramsList", list);
			FreemakerUtil.createJavaFile(table_en_name, map, basePackage,path);
			Class<?> claz = BuildEntityClass.getBuildClass(path, String.valueOf(map.get("className")), basePackage);
			ClassUtil.putClass(claz);
			String resultSql = sql.substring(0, sql.lastIndexOf(","));
			resultSql += ")";
			
			dynamicFormServiceImpl.createTable(resultSql);
			
			Table_Info info = new Table_Info();
			info.setTable_info(jsonStr);
			info.setTable_en_name(table_en_name);
			info.setTable_cn_name(table_cn_name);
			info.setShowTime(DateTools.getCurrentDate());
			info.setCreateTime(DateTools.getCurrentDateLong());
			
			dynamicFormServiceImpl.insertTableInfo(info);
			
			List<Table_Info> listTable = dynamicFormServiceImpl.getTabelInfoList();
			JSONArray menuja = new JSONArray();
			for(Table_Info t:listTable){
				JSONObject ob = new JSONObject();
				JSONObject json = new JSONObject();
				json.put("table_name", t.getTable_en_name());
				
				ob.put("id", t.getTable_id());
				ob.put("text", t.getTable_cn_name());
				ob.put("url", "/web/table_info.jsp");
				ob.put("params", json);
				ob.put("children", new JSONArray());
				menuja.add(ob);
			}
			String jsonpath = request.getServletContext().getRealPath("config")+File.separator+"menu.json";
			FileOutputStream out = new FileOutputStream(new File(jsonpath));
			out.write(menuja.toString().getBytes("UTF-8"));
			out.flush();
			out.close();
			
			resultJson.put("status", 1);
			resultJson.put("msg", "成功!");
		}catch(Exception e){
			e.printStackTrace();
		}
		resultJson.put("status", 0);
		resultJson.put("msg", "失败!");
		
		outData(response, resultJson);
	}
	
	@RequestMapping(params = "method=getList")
	@ResponseBody
	public void getList(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String tableName = request.getParameter("name");
		String start = (request.getParameter("start") == null || "".equals(request.getParameter("start")) )  ? "0" : request.getParameter("start");
		
		String limit = (request.getParameter("limit") == null 
				|| "".equals(request.getParameter("limit")) ) ? "0" : request.getParameter("limit");
		String jonStr = (request.getParameter("jsonStr") == null 
				|| "".equals(request.getParameter("jsonStr")) ) ? new JSONObject().toString() : request.getParameter("jsonStr");
		
		Map<String, Object> map = dynamicFormServiceImpl.getMap(tableName,JSONObject.fromObject(jonStr),
										(Integer.valueOf(start) - 1) * Integer.valueOf(limit),Integer.valueOf(limit));
		
		outData(response, map);
		
	}
	@RequestMapping(params = "method=addOrUpdateModel")
	@ResponseBody
	public void addModel(HttpServletRequest request,HttpServletResponse response) throws Exception {
		JSONObject resultJson = new JSONObject();
		try{
			String tableName = request.getParameter("name");
			String jsonStr = request.getParameter("jsonStr");
			
			JSONObject json = JSONObject.fromObject(jsonStr);
			
			if(StringUtils.isEmpty(json.getString("table_id"))){
				json.put("createTime", DateTools.getCurrentDateLong());
				json.put("showTime", DateTools.getCurrentDate());
				dynamicFormServiceImpl.insert(json, tableName);
			}else{
				dynamicFormServiceImpl.update(JSONObject.fromObject(jsonStr), tableName);
			}
			
			resultJson.put("status", 1);
			resultJson.put("msg", "成功!");
		}catch(Exception e){
			e.printStackTrace();

			resultJson.put("status", 0);
			resultJson.put("msg", "失败!");
			
		}
		outData(response, resultJson);
	}
	@RequestMapping(params = "method=updateModel")
	@ResponseBody
	public void updateModel(HttpServletRequest request,HttpServletResponse response) throws IOException{
		JSONObject resultJson = new JSONObject();
		try{
			String tableName = request.getParameter("name");
			String jsonStr = request.getParameter("jsonStr");
			
			dynamicFormServiceImpl.update(JSONObject.fromObject(jsonStr), tableName);
			resultJson.put("status", 1);
			resultJson.put("msg", "成功!");
		}catch(Exception e){
			e.printStackTrace();

			resultJson.put("status", 0);
			resultJson.put("msg", "失败!");
		}
		
		outData(response, resultJson);
	}
	@RequestMapping(params = "method=deleteModel")
	@ResponseBody
	public void deleteModel(HttpServletRequest request,HttpServletResponse response) throws IOException{
		JSONObject resultJson = new JSONObject();
		try{
			String tableName = request.getParameter("name");
			String jsonStr = request.getParameter("jsonStr");
			
			dynamicFormServiceImpl.delete(tableName,JSONObject.fromObject(jsonStr));
			
			resultJson.put("status", 1);
			resultJson.put("msg", "成功!");
		}catch(Exception e){
			e.printStackTrace();

			resultJson.put("status", 0);
			resultJson.put("msg", "失败!");
		}
		
		outData(response, resultJson);
	}
	@RequestMapping(params = "method=getTableInfoByEnName")
	@ResponseBody
	public void getTableInfoByEnName(Table_Info model,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Table_Info t = dynamicFormServiceImpl.getTableInfoByEnName(model.getTable_en_name());
		outData(response, t);
	}
	
	@RequestMapping(params = "method=uploadFile")
	@ResponseBody
	public void uploadFile(@RequestParam("file") MultipartFile file ,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String path = FileUpload.uploadFile(file, request);
		String pathId = request.getParameter("uploadFilePathId");
		String url = request.getContextPath()+"/" + path;
		System.out.println(path);
		System.err.println(pathId);
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		sb.append("window.parent.document.getElementById('"+pathId+"').value = ");
		sb.append("'"+url+"';");
		sb.append("alert('上传成功:"+file.getOriginalFilename()+"')");
		sb.append("</script>");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(sb.toString());
		response.getWriter().close();
		response.getWriter().flush();
	}
}
